const jwt = require('jsonwebtoken')
const config = require('../config')

module.exports = function (req, res, next) {
  // 接口鉴权,请求头中包含有效的authorization字段,access_token
  const access_token = req.header('authorization')
  // 检测是否存在access_token
  if (!access_token) {
    return res.status(200).json({
      code: 401,
      msg: 'Unauthorization无token'
    })
  }
  let userData = ''
  try {
    userData = jwt.verify(access_token, config.jwtPrivateKey)
    // 得到了token中存储的数据id
    req.userData = userData
  } catch (err) {
    return res.status(200).json({
      code: 401,
      msg: '无效token'
    })
  }
  next()
}
